package com.dragon.connector.imServer.server;

import com.dragon.connector.imServer.initializer.WebSocketInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Slf4j
@Component
public class WebSocketConnector {

    @Value("${netty.websocket.port}")
    private int port;

    /**
     * 主线程线程组
     */
    private NioEventLoopGroup boss;

    /**
     * 子线程线程组
     */
    private NioEventLoopGroup work;

    /**
     * netty 服务组件
     */
    private ServerBootstrap serverBootstrap = new ServerBootstrap();

    @PostConstruct
    public void run() throws InterruptedException {
        boss = new NioEventLoopGroup(1);
        work = new NioEventLoopGroup();
        // 组装监听socket
        serverBootstrap.group(boss, work)
                // 设置socket监听通道
                .channel(NioServerSocketChannel.class);
                // 设置连接option选项
        //3 设置监听端口
//        String ip = IOUtil.getHostAddress();
        String ip = "127.0.0.1";
        serverBootstrap.localAddress(new InetSocketAddress(ip, port));
        serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                // 设置输出日志
                .handler(new LoggingHandler(LogLevel.INFO))
                // 初始化通道配置
                .childHandler(new WebSocketInitializer());
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        if(channelFuture.isSuccess()){
            log.info("IM websocket服务启动成功, 端口为： " +
                    channelFuture.channel().localAddress());
        }
    }

    @PreDestroy
    public void destory(){
        boss.shutdownGracefully().syncUninterruptibly();
        work.shutdownGracefully().syncUninterruptibly();
        log.info("IM websocket服务已经关闭");
    }
}
